<?php
class Toolbar extends AbstractFilter {

	public $pageSize;
	
	public $order;
	
	public $direction;
	
	protected $_criteria = null;

	public function init($criteria) {
		$this->_criteria = $criteria;
		
		// retrieve toolbar setting
		$setting = array();
		$this->_applyDefaultSetting($setting);
		$this->_applyCookieSetting($setting);
		$this->_applyClientSetting($setting);

		// apply setting
		foreach($setting as $name => $value)
			$this->$name = $value;
	}
	
	protected function _applyDefaultSetting(array &$data) {
		$data['pageSize'] = 50;
		$data['order'] = 'date';
		$data['direction'] = 'desc';
	}
	
	protected function _applyCookieSetting(array &$data) {
		$cData = Helper::getCookie('frontend', 'toolbar');
		if (!is_array($cData)) {
			$cData = array();
			Helper::setCookie('frontend', 'toolbar', $cData);
		}
		$data = array_merge($data, $cData);
	}
	
	protected function _applyClientSetting(array &$data) {
		if (isset($_GET['limit'])) {
			$data['pageSize'] = $_GET['limit'];
		}
		
		if (isset($_GET['order'])) {
			$data['order'] = $_GET['order'];
		}
		
		if (isset($_GET['dir'])) {
			$data['direction'] = $_GET['dir'];
		}
		
		Helper::setCookie('frontend', 'toolbar', $data);
	}

	public function apply() {
		// apply page size
		$this->_criteria->limit = $this->pageSize;
		
		// apply order
		switch($this->order) {
			case 'title':
				$order = "title {$this->direction}";
				break;
			case 'date':
				$order = "updated_time {$this->direction}";
				break;
			case 'rating':
				$order = "rating {$this->direction}";
				break;
		}
		$this->_criteria->order = $order;
	}

	public function getTemplate() {
		return '/catalog/toolbar';
	}

	public function getAvailablePageSizes() {
		return array(10, 30, 50);
	}
	
	public function getAvailableOrders() {
		return array(
			'date'=>'Date', 
			'title'=>'Title', 
			'rating'=>'Rating'
		);
	}

	public function getPageSizeListData() {
		$ps = $this->getAvailablePageSizes();
		return array_combine($ps, $ps);
	}

	public function getDirectionUrl() {
		$params = $_GET;
		$params['dir'] = $this->direction=='asc'? 'desc' : 'asc';
		return Yii::app()->createUrl('site/index', $params);
	}
}